/*
 * @Author: yangzonglong
 * @Date: 2021-05-13 11:26:39
 * @version: v1.0.0
 * @Descripttion: 读取form表单列表
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-07-21 14:49:26
 * @Auditor: 
 */
import React, { useEffect, useContext, useState, useRef, useCallback } from 'react';
import { Modal } from 'antd';
import { Table } from '@library';
import { TableRefProps } from '@library/components/table/interface';
import context from '../context';
import { getForm } from './../Api';
import formContentToObj from './../../../utils/formContentToObj';
import { FormField, StartEventSelfProps } from './../../../interface';

const T = window.$app.t;
const START_EVENT = 'bpmn:StartEvent';

const bodyStyle: React.CSSProperties = {
  display: 'flex',
  height: '500px',
  flexDirection: 'column'
}

const columns = [
  { title: T('fieldNames'), dataIndex: 'fieldName' },
  { title: T('fieldNamesDesc'), dataIndex: 'name' },
  { title: T('fieldNamesType'), dataIndex: 'type' }
]
interface FormVariableProps {
  visible: boolean;
  onCancel(): void;
  onOk(data: FormField[]): void;
  all?: boolean; // 只对gform表单有效，为true时 则会把所有控件罗列出来，反之只取 “表单” 控件
  title?: string
}

export default ({ visible, onCancel, onOk, all, title }: FormVariableProps) => {
  const tableRef = useRef<TableRefProps>(null);
  const { self } = useContext(context);
  const [formVariable, setFormVariable] = useState<FormField[]>([]);

  useEffect(() => {
    const children = self.parent?.children || [];
    const startEvent = children.find(item => item.type === START_EVENT) as StartEventSelfProps;
    const formId = startEvent?.businessObject?.formPageId;

    if (!formId) return;

    getForm(formId).then(result => {
      if (result) {
        const list = formContentToObj(result, all)
        const filterList = list.filter(item => {
          if (item.type === 'input') {
            const options = JSON.parse(item.options)
            if (options?.formItemProps?.hideInput) return false
            return true
          }
          return true
        })

        setFormVariable(filterList);
      }

    })

  }, [self, all]);

  const _onOk = useCallback(async () => {
    const rows = tableRef.current?.getSelectedRows();
    onOk(rows as FormField[]);
  }, [onOk]);

  return (
    <Modal
      destroyOnClose
      onOk={_onOk}
      width={800}
      visible={visible}
      onCancel={onCancel}
      title={title || T('formVar')}
      bodyStyle={bodyStyle}>
      <Table
        ref={tableRef}
        rowSelectionType='checkbox'
        columns={columns}
        dataSource={formVariable}
        rowKey='fieldName' />
    </Modal>
  )
}
